﻿using System.IO;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.TextTemplating;

namespace CodeGeneration.Artech
{
    public abstract class Template : TextTransformation
    {
        private bool _initialized;

        public override void Initialize()
        {
            base.Initialize();
            _initialized = true;
        }
        internal void EnsureInitialized()
        {
            if (!_initialized)
            {
                Initialize();
            }
        }
        public virtual void Render()
        {
            TransformContext.EnsureContextInitialized();
            string contents = TransformText();
            TransformContext.Current.Transformation.Write(contents);
        }
        public virtual void RenderToFile(string fileName)
        {
            TransformContext.EnsureContextInitialized();
            string directory = Path.GetDirectoryName(TransformContext.Current.Host.TemplateFile);
            if (directory != null) fileName = Path.Combine(directory, fileName);
            string contents = TransformText();
            CreateFile(fileName, contents);
            if (TransformContext.Current.TemplageProjectItem.ProjectItems.Cast<ProjectItem>().Any(item => item.FileNames[0] != fileName))
            {
                TransformContext.Current.TemplageProjectItem.ProjectItems.AddFromFile(fileName);
            }
        }
        protected void CreateFile(string fileName, string contents)
        {
            if (File.Exists(fileName) && File.ReadAllText(fileName) == contents)
            {
                return;
            }
            SourceControl sourceControl = TransformContext.Current.Dte.SourceControl;
            if (null != sourceControl && sourceControl.IsItemUnderSCC(fileName) && !sourceControl.IsItemCheckedOut(fileName))
            {
                sourceControl.CheckOutItem(fileName);
            }
            File.WriteAllText(fileName, contents);
        }
    }
}